
import '../pojo/ImPojo.dart';
import '../util/DateUtil.dart';
import '../util/ImSingleton.dart';
import 'package:sqflite/sqflite.dart';

import '../util/MapUtil.dart';
import 'BaseDao.dart';

class SettingDao extends BaseDao {

  Future<ImSetting?> getByName(String userId, String name) async {
    Database? database = getDatabase(); //ImSingleton.getInstance()?.dataBase;
    List? list = await database?.rawQuery("select * from im_setting where name = ? and currentUserId = ? limit 1",
        [name, userId]);
    if (list != null && list.length > 0) {
      return Future.value(_toImSetting(list[0]));
    }
    return null;
  }

  Future<void> update(String userId, String name, String value) async {
    Database? database = getDatabase(); //ImSingleton.getInstance()?.dataBase;
    int? n = await database?.rawUpdate("update im_setting set value = ?, updateTime = ? where name = ? and currentUserId = ?",
        [value, DateUtil.formatDate(DateTime.now()), name, userId]);
    assert(n != null && n > 0, "setting更新失败！");
  }

  Future<int> insert(String userId, String name, String value) async {
    Database? database = getDatabase(); //ImSingleton.getInstance()?.dataBase;
    var data = _toMap(userId, name, value);
    int? id = await database?.insert("im_setting", data);
    assert(id != null && id > 0, "setting insert error");
    return id!;
  }

  Map<String, Object?> _toMap(String userId, String name, String value) {
    Map<String, Object?> map = {};
    map['name'] = name;
    map['currentUserId'] = userId;
    map['value'] = value;
    map['createTime'] = DateUtil.formatDate(DateTime.now());
    map['updateTime'] = DateUtil.formatDate(DateTime.now());
    return map;
  }

  ImSetting _toImSetting(Map<String, Object?> map) {
    var setting = ImSetting(name: MapUtil.getString(map, "name"), currentUserId: MapUtil.getString(map, "currentUserId"));
    setting.description = MapUtil.getStringOrNull(map, "description");
    setting.value = MapUtil.getString(map, 'value');
    setting.ext1 = MapUtil.getStringOrNull(map, 'ext1');
    setting.ext2 = MapUtil.getStringOrNull(map, 'ext2');
    setting.createTime = MapUtil.getDate(map, "createTime");
    setting.updateTime = MapUtil.getDate(map, "updateTime");
    return setting;
  }
}